//
//  UserAccount.swift
//  HJWeibo
//
//  Created by huangjiong on 16/2/4.
//  Copyright © 2016年 huangjiong. All rights reserved.
//

import UIKit
import SVProgressHUD

class UserAccount: NSObject,NSCoding {
    
    /// 用于调用access_token，接口获取授权后的access token。
    var access_token: String?
    /// access_token的生命周期，单位是秒数。
    var expires_in: NSNumber?{
        didSet{
            expires_Date = NSDate(timeIntervalSinceNow: expires_in!.doubleValue)
        }
    }
    
    /// 当前授权用户的UID。
    var uid:String?
    
    //保存用户过期时间
    var expires_Date: NSDate?
    
    //呢称
    var screen_name: String?
    //头像
    var avatar_large:String?
    
    override init() {
        
        super.init()
    }
    
    init(dict: [String: AnyObject]) {
        super.init()
        /*
        access_token = dict["access_token"] as? String
        expires_in = dict["expires_in"] as? NSNumber
        uid = dict["uid"] as? String
        */
        setValuesForKeysWithDictionary(dict)
    }
    
    override func setValue(value: AnyObject?, forUndefinedKey key: String) {
        
    }
    
    
    
    /**
     给外部提供一个方法,获取用户信息
     */
    func loadUserInfo(finished: (account:UserAccount?,error:NSError?)->())
    {
        let path = "2/users/show.json"
        let paramater = ["access_token":access_token!,"uid":uid!]
        //网络获取
        HJNetworkManager.sharedManager().GET(path, parameters: paramater, progress: { (_) -> Void in
            
            }, success: { (_, JSON) -> Void in
                
                //字典有值时,再使用
                if let dict = JSON as? [String:AnyObject]
                {
                    self.screen_name = dict["screen_name"] as? String
                    self.avatar_large = dict["avatar_large"] as? String
                    //回调
                    finished(account: self,error: nil)
                }
                 finished(account: nil,error: nil)
                           
            }) { (_, error) -> Void in
                finished(account: nil,error: nil)
        }
        
    }
    
    
    
    //返回用户是否已经登录
    class func userIsLogin() -> Bool
    {
        return UserAccount.loadAccount() != nil
    }
    
    //保存模型
    func saveAccount()
    {
        NSKeyedArchiver.archiveRootObject(self, toFile: "account.plist".cacheDir())
    }
    
    //取模型,也即加载模型
    static var account: UserAccount?
    class func loadAccount() -> UserAccount?
    {
         //先判断是否已经加载过
        if account != nil
        {
            return account
        }
        
        //加载
         account = NSKeyedUnarchiver.unarchiveObjectWithFile("account.plist".cacheDir()) as? UserAccount
        if account?.expires_Date?.compare(NSDate()) == NSComparisonResult.OrderedAscending
        {
            //已经过期了
            return nil
        }
        
        return account
    }
    
    //归档
    func encodeWithCoder(aCoder: NSCoder) {
        
        aCoder.encodeObject(access_token, forKey: "access_token")
        aCoder.encodeObject(expires_in, forKey: "expires_in")
        aCoder.encodeObject(uid, forKey: "uid")
        aCoder.encodeObject(expires_Date, forKey: "expires_Date")
        aCoder.encodeObject(screen_name, forKey: "screen_name")
        aCoder.encodeObject(avatar_large, forKey: "avatar_large")
    }
    
    //解归档
    required  init?(coder aDecoder: NSCoder) {
        
        access_token = aDecoder.decodeObjectForKey("access_token") as? String
        expires_in = aDecoder.decodeObjectForKey("expires_in") as? NSNumber
        uid = aDecoder.decodeObjectForKey("uid") as? String
        expires_Date = aDecoder.decodeObjectForKey("expires_Date") as? NSDate
        screen_name = aDecoder.decodeObjectForKey("screen_name") as? String
        avatar_large = aDecoder.decodeObjectForKey("avatar_large") as? String
    }
    
}


